<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2023-01-24
 * Time: 10:16
 */

namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Enums\Constant;
use App\Enums\CouponEnums;
use App\Inputs\PageInput;
use App\Services\Promotion\CouponServices;
use App\Models\Promotion\CouponUser;
use Illuminate\Support\Carbon;

class CouponController extends WxController
{
    protected $except = ["list"];

    public function list() {
        $page = PageInput::new();
        $columns = ["id", "name", "desc", "tag", "discount", "min", "days", "start_time", "end_time"];
        $list = CouponServices::getInstance()->list($page, $columns);
        return $this->successPaginate($list);
    }
    
    public function mylist() {
        $status = $this->verifyInteger('status');
        $page = PageInput::new();
        // 获取用户领取的优惠券
        $list = CouponServices::getInstance()->mylist($this->userId(), $status, $page);
        $couponUserList = collect($list->items());
        $couponIds = $couponUserList->pluck('coupon_id')->toArray();

        //获取用户领取的优惠券信息
        $coupons = CouponServices::getInstance()->getCoupons($couponIds)->keyBy('id');
        $mylist = $couponUserList->map(function (CouponUser $item) use ($coupons) {
            $coupon = $coupons->get($item->coupon_id);
            return [
                'id' => $item->id,
                'cid' => $coupon->id,
                'name' => $coupon->name,
                'desc' => $coupon->desc,
                'tag' => $coupon->tag,
                'min' => $coupon->min,
                'discount' => $coupon->discount,
                'startTime' => $item->start_time,
                'endTime' => $item->end_time,
                'available' => false
            ];
        });
        $list = $this->paginate($list, $mylist);
        return $this->success($list);
    }

    public function receive() {
        $couponId = $this->verifyId('couponId', 0);
        CouponServices::getInstance()->receive($this->userId(), $couponId);
        return $this->success();
    }
}